﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WhittleList.Controllers;
using WhittleList.Bll;
using System.Web.Routing;

namespace WhittleList.ModelBinder
{
    public class SiteRoute
    {
    }

    public class SiteModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext.Controller is BaseController)
            {
                BaseController controller = (BaseController)controllerContext.Controller;
                Site site = null;
                if (controllerContext.RouteData.Values["siteName"] != null)
                {
                    site = controller.SiteRepository.Site_GetByName(controllerContext.RouteData.Values["siteName"].ToString());
                }

                if (site == null && controllerContext.RouteData.Values["siteUrl"] != null)
                {
                    site = controller.SiteRepository.Site_GetByUrl(controllerContext.RouteData.Values["siteUrl"].ToString());
                }

                if (site == null)
                {
                    string url = controllerContext.HttpContext.Request.ServerVariables["SERVER_NAME"];
                    site = controller.SiteRepository.Site_GetByUrl(url);
                }
                return site;
            }
            else
            {
                throw new InvalidCastException(string.Format("Controller is of typeof '{0}' which cannot be cast to a WhittleList.Controllers.BaseController. The Site Action Filter can only be used with controllers that inherit from WhittleList.Controllers.BaseController", controllerContext.Controller.GetType()));
            }
        }
    }
}
